package com.kx.kxpicture.aop;

import com.kx.kxpicture.annotation.AuthCheck;
import com.kx.kxpicture.exception.BusinessException;
import com.kx.kxpicture.exception.ErrorCode;
import com.kx.kxpicture.model.entity.User;
import com.kx.kxpicture.model.enums.UserRoleEnum;
import com.kx.kxpicture.service.UserService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 用户权限判断
 *
 * @author kuangxin
 * date 2025/8/15
 */
@Aspect
@Component
public class AuthInterceptor {
    @Resource
    UserService userService;

    @Around("@annotation(authCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        //获取request对象，得到登录用户
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        User loginUser = userService.getLoginUser(request);
        String mustRole = authCheck.mustRole();
        UserRoleEnum mustRoleEnum = UserRoleEnum.getEnum(mustRole);
        //得到用户具有的权限
        String userRole = loginUser.getUserRole();
        UserRoleEnum userRoleEnum = UserRoleEnum.getEnum(userRole);
        //判断是否要有权限
        if (mustRoleEnum==null){
            //不需要放行
            return joinPoint.proceed();
        }
        if (userRoleEnum==null){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        //是否是管理员权限
        if (UserRoleEnum.ADMIN.equals(mustRoleEnum)&&!UserRoleEnum.ADMIN.equals(userRoleEnum)){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        return joinPoint.proceed();
    }

}
